package com.pdool.game.logic.service;

import com.pdool.common.constants.Constant;
import com.pdool.common.constants.MsgId;
import com.pdool.common.dto.room.ClientRoomMsg;
import com.pdool.common.msg.common.NullReq;
import com.pdool.game.constant.SessionAttr;
import com.pdool.game.core.config.GameConfig;
import com.pdool.game.core.msg.RoomRemoteMgr;
import com.pdool.game.logic.enums.LogPointType;
import com.pdool.game.logic.mgr.MatchMgr;
import com.pdool.game.logic.mgr.UserMgr;
import com.pdool.game.logic.util.LogUtil;
import com.pdool.game.util.SessionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.util.Map;
/**
 * 登录逻辑处理类
 */
@Component
@Slf4j
public class LoginService {
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    private GameConfig gameConfig;
    public void logOut(WebSocketSession session) {
        if (session == null) {
            return;
        }
        redisTemplate.opsForHash().increment(Constant.GAME_ONLINE_COUNT,gameConfig.getServerId(),-1);
        for (Map.Entry<Long, WebSocketSession> entry : UserMgr.getInstance().getSessionMap().entrySet()) {
            if (entry.getValue().equals(session)) {
                long roleId = entry.getKey();
                if (session.getAttributes().containsKey(SessionAttr.LOGIN_TIME)) {
                    Long loginTime = (Long) session.getAttributes().get(SessionAttr.LOGIN_TIME);
                    long sec = (System.currentTimeMillis() - loginTime) / 1000;
                    LogUtil.getInstance().recordLog(roleId, LogPointType.DAY_IN_GAME, sec);
                }

                Map<Long, String> roleRoomMap = MatchMgr.getInstance().getRoleRoomMap();

                if (roleRoomMap.containsKey(roleId)) {
                    String roomId = roleRoomMap.get(roleId);
                    ClientRoomMsg clientRoomMsg = new ClientRoomMsg();
                    clientRoomMsg.setMsgId(MsgId.QUIT_FIGHT);
                    clientRoomMsg.setRoleId(roleId);
                    clientRoomMsg.setMsg(NullReq.newBuilder().build().toByteArray());
                    RoomRemoteMgr.getInstance().getRoomService().trans2Room(roomId, clientRoomMsg);
                }
                UserMgr.getInstance().getSessionMap().remove(roleId);
                SessionUtil.closeSession(session);
                return;
            }
        }
    }
}
